package com.waa.gulimall.product.controller;

import com.waa.gulimall.product.entity.CategoryEntity;
import com.waa.gulimall.product.service.CategoryService;
import com.waa.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
public class IndexController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedissonClient redisson;

    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model) {
        List<CategoryEntity> categoryEntities = categoryService.getLeve1Categorys();
        model.addAttribute("catagorys", categoryEntities);
        return "index";
    }

    @GetMapping("/index/catalog.json")
    @ResponseBody
    public Map<String, List<Catelog2Vo>> getCatelogJson() {
        final Map<String,  List<Catelog2Vo>> catalogJson = categoryService.getCatalogJson();
        return  catalogJson;
    }
    @GetMapping("/hello")
    @ResponseBody
    public String hello(){
        //获取一把锁只要锁的名字一样，就是同一把锁
        final RLock mylock = redisson.getLock("mylock");
        //加锁
        mylock.lock();//阻塞式等待,默认加锁时间为30s
        //锁的自动续期如果业务超长，运行期间自动给锁续上新的时间30s
        //加锁的业务完成后，就不会再给当前锁续期，即使不手动解锁，30s后也会自动释放锁
        try {
            System.out.println("加锁成功"+Thread.currentThread().getName());
            Thread.sleep(30000);
        } catch (Exception e) {

        }finally {
            mylock.unlock();
        }
        return "hello";
    }
    
}
